﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;

namespace Apps.WebApi.Core
{
    public class CoreCommon
    {
        /// <summary>
        /// 返回JSON格式给客户端
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }

            //add
            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //string jsonstring = serializer.Serialize(Data);


            //string p = @"\\/Date\((\d+)\+\d+\)\\/";

            string p = @"\\/Date\(\d+\)\\/";

            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);

            Regex reg = new Regex(p);

            str = reg.Replace(str, matchEvaluator);
            //end

            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        /// <summary>
        /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
        /// </summary>
        private static string ConvertJsonDateToDateString(Match m)
        {

            string result = string.Empty;

            string p = @"\d";
            var cArray = m.Value.ToCharArray();
            StringBuilder sb = new StringBuilder();

            Regex reg = new Regex(p);
            for (int i = 0; i < cArray.Length; i++)
            {
                if (reg.IsMatch(cArray[i].ToString()))
                {
                    sb.Append(cArray[i]);
                }
            }
            // reg.Replace(m.Value;

            //DateTime dt = new DateTime(1970, 1, 1);

            //dt = dt.AddMilliseconds(long.Parse(sb.ToString()));

            //dt = dt.ToLocalTime();

            //result = dt.ToString("yyyy-MM-dd HH:mm:ss");

            result = sb.ToString();
            return result;

        }
    }
}